export default class WriteData extends zrender.Group {
	constructor(node) {
		super();
	    this.node = node;
	    this.init();
		this.table = null;
		this.tableData = null;
		window.writeData = this;
	}
	init() {
	    // this.beforeCreate();
	    // this.create();
	}
	beforeCreate() {
	    // this.dialog = $('#myModal');
		// $(".smartTableDiv").html("");
		var nodeId = this.node.getId();
		console.log("nodeId:"+nodeId);
		$.ajax({
			  url : "http://localhost:8081/tree/getNodeData?nodeId="+nodeId,
			  type : "POST",
			  contentType: "application/json;charset=UTF-8",
			  dataType: "json",
			  data : '',
			  success : function(data){
				  console.log("getNodeData success:"+data);
				  window.writeData.tableData = data;
				  window.writeData.create();
			  },
			  error : function(xhr,status,error) {
				  console.log("error:"+status+","+error);
			  }
		});
	}
	create() {
		// this.dialog.modal("show");
		this.dialog = $('#myModal');
		this.dialog.find('.modal-title').text(this.node.getText());
		
		// var t = {
		// 	data : [ //表格内json数据,可为空
		// 		{th:"属性",td:["key1", "key2", "key3" ,"key4", "key5"]},
		// 		{th:"内容",td:["value1", "value2", "value3" ,"value4", "value5"]}
		// 	]
		// };
		var t = {
			data : [ //表格内json数据,可为空
				{th:"属性",td:[]},
				{th:"内容",td:[]}
			]
		};
		var jsonArr = this.tableData.data;
		for (var i in jsonArr) {
			var item = jsonArr[i];
			for(var key in item) {
				t.data[0].td.push(key);
				t.data[1].td.push(item[key]);
			}
		}
		
		console.log("table t:"+JSON.stringify(t));
		
		this.table = $(".smartTableDiv").smartTable({
			editText:true, //是否可编辑单元格内容
			editRow :true, //是否可操作单元行，添加或删除
			addBtnBg:["url(images/addbtn.png) no-repeat","url(images/addbtn_hover.png)"],//添加按钮自定义，若覆盖和移除背景相同，两项需写一样的内容
			delBtnBg:["url(images/delete.png) 2px 6px no-repeat", "url(images/delete.png) 2px 6px no-repeat"],//删除按钮自定义
			tableContent:t.data
		});
		window.st = this.table;
		window.st.nodeId = this.node.getId();
		this.dialog.find("#submit").click(function(){
			var json = $(".smartTableDiv").smartTable.getData();
			var keys = json.data[0].td;
			var values = json.data[1].td;
			
			var data = JSON.parse('{"nodeId":'+window.st.nodeId+',"data":[]}');
			for(var i=0;i<keys.length;i++) {
				data.data.push(JSON.parse('{"'+keys[i]+'":"'+values[i]+'"}'));
			}
			
			var data = JSON.stringify(data);
			console.log("table data:"+data);
			// console.log("table data:"+JSON.stringify(data));
			$.ajax({
				  url : "http://localhost:8081/tree/nodeData",
				  type : "POST",
				  contentType: "application/json;charset=UTF-8",
				  dataType: "json",
				  data : data,
				  success : function(data){
					  console.log("success");
				  },
				  error : function(xhr,status,error) {
					  console.log("error:"+status+","+error);
				  }
			});
		});
		this.dialog.modal("show");
	}
	show() {
		this.beforeCreate();
	}
}